<template>
  <div class="task-search">
    <el-select
      :id="`form_${field.fieldName}`"
      :value="value"
      value-key="taskNo"
      :remote-method="keywordSearch"
      :placeholder="$t('common.placeholder.inputKeyWordToSearch')"
      remote
      clearable
      filterable
      v-el-select-loadmore="loadMoreOptions"
      @focus="focus"
      @change="changeSelect"
    >
      <el-option
        v-for="item in options"
        :key="item.taskNo"
        :label="item.taskNo"
        :value="item"
        
      >
      </el-option>
    </el-select>
  </div>
</template>

<script>
import { isArray } from '@src/util/type'
import { defineComponent, ref, computed } from 'vue';
import { debounce } from 'lodash';
import { search as taskSearch } from '@src/api/TaskApi';

export default defineComponent({
  name: 'connector-related-task-search', // 工单搜索
  props: {
    field: {
      type: Object,
      default: null,
    },
    value: {
      type: Object | Array,
      default: null,
    },
  },
  emits: ['update'],
  setup(props, { emit }) {
    const loading = ref(false);
    const page = ref(1);
    const options = ref(props.value && !isArray(props.value) ? [props.value] : []);
    const keyword = ref('');
    const hasNextPage = ref(true);

    // 改变值
    function changeSelect(value) {
      if(!value) return emit('update', {});
      const { id, taskNo, templateId } = value
      const related_task = {
        taskId: id,
        taskNo,
        templateId
      }

      emit('update', related_task);
    }

    const search = debounce(async () => {
      if (loading.value) return;
      loading.value = true;
      try {
        const res = await taskSearch({
          keyword: keyword.value,
          page: page.value,
        });
        if (page.value === 1) {
          options.value = [];
        }
        options.value.push(...(res.result?.content || []));
        hasNextPage.value = res.result.totalPages > page.value;
      } catch (error) {
        console.error('searchTaskManager function catch err', error);
      } finally {
        loading.value = false;
      }
    });

    function keywordSearch(_keyword) {
      page.value = 1;
      keyword.value = _keyword;
      search();
    }

    const loadMore = debounce(() => {
      if (!hasNextPage.value || loading.value) return;
      page.value++;
      search();
    });

    function focus() {
      if (options.length) return;
      keywordSearch();
    }

    const loadMoreOptions = computed(() => ({
      disabled: loading.value,
      callback: loadMore,
      distance: 10,
    }));

    return {
      options,
      loadMoreOptions,

      changeSelect,
      focus,
      keywordSearch,
    };
  },
});
</script>

<style></style>
